package com.tuyrt.`as`.proj.main.biz.detail

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.tuyrt.`as`.proj.common.ui.component.HiBaseActivity
import com.tuyrt.`as`.proj.main.R
import com.tuyrt.`as`.proj.main.biz.account.AccountManager
import com.tuyrt.`as`.proj.main.fragment.home.GoodsItem
import com.tuyrt.`as`.proj.main.model.DetailModel
import com.tuyrt.`as`.proj.main.model.GoodsModel
import com.tuyrt.`as`.proj.main.model.selectPrice
import com.tuyrt.`as`.proj.main.route.HiRoute
import com.tuyrt.hi.library.util.HiStatusBar
import com.tuyrt.hi.ui.empty.EmptyView
import com.tuyrt.hi.ui.item.HiAdapter
import com.tuyrt.hi.ui.item.HiDataItem
import kotlinx.android.synthetic.main.activity_detail.*

/**
 * author: Administrator on 2021/7/15.
 * desc:
 */
@Route(path = "/detail/main")
class DetailActivity : HiBaseActivity() {

    private var emptyView: EmptyView? = null
    private lateinit var viewModel: DetailViewModel

    @JvmField
    @Autowired
    var goodsId: String? = null

    @JvmField
    @Autowired
    var goodsModel: GoodsModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        HiStatusBar.setStatusBar(this, true, Color.TRANSPARENT, true)
        HiRoute.inject(this)
        assert(!TextUtils.isEmpty(goodsId)) { "goodsId must not be null" }

        setContentView(R.layout.activity_detail)
        initView()
        preBindData()

        viewModel = DetailViewModel.get(goodsId, viewModelStore)
        viewModel.pageData.observe(this) {
            if (it == null) {
                showEmptyView()
            } else {
                bindData(it)
            }
        }
        viewModel.queryGoodsDetail()
    }

    private fun initView() {
        action_back.setOnClickListener { onBackPressed() }

        recycler_view.layoutManager = GridLayoutManager(this, 2)
        recycler_view.adapter = HiAdapter(this)
        recycler_view.addOnScrollListener(TitleScrollListener {
            title_Bar.setBackgroundColor(it)
        })
    }

    private fun preBindData() {
        if (goodsModel == null) return

        val hiAdapter = recycler_view.adapter as HiAdapter
        hiAdapter.addItemAt(0, HeaderItem(
            goodsModel!!.sliderImages,
            selectPrice(goodsModel!!.groupPrice, goodsModel!!.marketPrice),
            goodsModel!!.completedNumText,
            goodsModel!!.goodsName
        ), false)
    }

    private fun bindData(detailModel: DetailModel) {
        recycler_view.visibility = View.VISIBLE
        emptyView?.visibility = View.GONE

        val hiAdapter = recycler_view.adapter as HiAdapter
        val dataItems = mutableListOf<HiDataItem<*, *>>()
        dataItems.add(HeaderItem(
            detailModel.sliderImages,
            selectPrice(detailModel.groupPrice, detailModel.marketPrice),
            detailModel.completedNumText,
            detailModel.goodsName
        ))
        // 评论
        dataItems.add(CommentItem(detailModel))
        //店铺
        dataItems.add(ShopItem(detailModel))
        //商品描述
        dataItems.add(GoodsAttrItem(detailModel))
        //图库
        detailModel.gallery?.forEach {
            dataItems.add(GalleryItem(it))
        }
        //相似商品
        detailModel.similarGoods?.let {
            dataItems.add(SimilarTitleItem())
            it.forEach {
                dataItems.add(GoodsItem(it, false))
            }
        }

        hiAdapter.clearItems()
        hiAdapter.addItems(dataItems, true)

        updateFavoriteActionFace(detailModel.isFavorite)
        updateOrderActionFace(detailModel)
    }

    @SuppressLint("SetTextI18n")
    private fun updateOrderActionFace(detailModel: DetailModel) {
        action_order.text = selectPrice(detailModel.groupPrice, detailModel.marketPrice) + getString(R.string.detail_order_action)

        action_order.setOnClickListener {
            // 点击立即购买 跳转 下单页
            toast("立即购买:${detailModel.goodsName}")
        }
    }

    private fun updateFavoriteActionFace(favorite: Boolean) {
        action_favorite.setOnClickListener {
            toggleFavorite()
        }

        action_favorite.setTextColor(
            ContextCompat.getColor(this, if (favorite) R.color.color_dd2 else R.color.color_999)
        )
    }

    private fun toggleFavorite() {
        if (!AccountManager.isLogin()) {
            AccountManager.login(this) { loginSuccess ->
                if (loginSuccess) {
                    toggleFavorite()
                }
            }
        } else {
            action_favorite.isClickable = false
            viewModel.toggleFavorite().observe(this) { success ->
                if (success != null) {
                    // 网络成功
                    updateFavoriteActionFace(success)
                    val message = if (success) getString(R.string.detail_favorite_success)
                    else getString(R.string.detail_cancel_favorite)
                    toast(message)
                } else {
                    // 网路失败
                }
                action_favorite.isClickable = true
            }
        }
    }

    private fun showEmptyView() {
        if (emptyView == null) {
            emptyView = EmptyView(this)
            emptyView!!.setIcon(R.string.if_empty3)
            emptyView!!.setDesc(getString(R.string.list_empty_desc))
            emptyView!!.layoutParams = ConstraintLayout.LayoutParams(-1, -1)
            emptyView!!.setBackgroundColor(Color.WHITE)
            emptyView!!.setButton(getString(R.string.list_empty_action), View.OnClickListener {
                viewModel.queryGoodsDetail()
            })

            root_container.addView(emptyView)
        }
        recycler_view.visibility = View.GONE
        emptyView!!.visibility = View.VISIBLE
    }


}